/*本模块功能:课程管理(管理员)
        编写者:朱光曜
        编写时间:2017.11.03*/
$(function() {
    var string1 = '<tr>' +
        '<th class="col-lg-2"><input type="checkbox" name="controlAll" id="controlAll" class="allCheck"></th>' +
        '<th class="col-lg-4">专业</th>' +
        '<th class="col-lg-4">课程名称</th>' +
        '<th class="col-lg-4">上课时间</th>' +
        '<th class="col-lg-4">上课地点</th>' +
        '<th class="col-lg-2">类型</th>' +
        '<th class="col-lg-3">操作</th>' +
        '</tr>';
    var confirm1 = new Confirm;
    var Alert1 = new Alert;
    var Alert2 = new Alert;

    function popup(data) { //弹出层

        var department = '<div class="simulation" departmentId="' + data.relationMsg.departmentId + '" relationId="' + data.relationMsg.relationId + '"  selectMark="' + data.relationMsg.selectMark + '" title="' + data.relationMsg.departmentName + '">' + data.relationMsg.departmentName + '</div>';

        var major = '<div class="simulation" professionId="' + data.relationMsg.professionId + '" title="' + data.relationMsg.professionName + '">' + data.relationMsg.professionName + '</div>';

        var curriculum = '<div class="simulation" courseId="' + data.relationMsg.courseId + '" title="' + data.relationMsg.courseName + '">' + data.relationMsg.courseName + '</div>';

        var teacher = '<div class="simulation" stuorteaId="' + data.relationMsg.stuorteaId + '" title="' + data.relationMsg.userName + '">' + data.relationMsg.userName + '</div>';

        var majorDirection = '<div class="simulation" mainId="' + data.relationMsg.mainId + '" title="' + data.relationMsg.directName + '">' + data.relationMsg.directName + '</div>';

        var lessonPlace = "";
        for(key in data.siteList) { //上课地点
            lessonPlace += '<option value="1" siteId="' + data.siteList[key].siteId + '">' + data.siteList[key].siteName + '</option>';
        }

        return '<div class="fl inputRight"><label for="departNames" class="fl">院&ensp;&ensp;&ensp;&ensp;系:&ensp;</label>' +

            department +

            '</div>' +
            '<div class="fl inputRight"><label for="departNames" class="fl">专&ensp;&ensp;&ensp;&ensp;业:&ensp;</label>' +

            major +

            '</div>' +
            '<div class="fl inputRight"><label for="departNames" class="fl">课程名称:&ensp;</label>' +

            curriculum +

            '</div>' +
            '<div class="fl inputRight"><label for="departNames" class="fl">任课教师:&ensp;</label>' +

            teacher +

            '</div>' +
            '<div class="fl inputRight"><label for="departNames" class="fl">专业方向:&ensp;</label>' +

            majorDirection +

            '</div>' +
            '<div class="fl inputRight"><label for="departNames">上课地点:&ensp;</label>' +
            '<select id="lessonPlace" class="publicSelect" >' +
            '<option value="1">请选择</option>' +
            lessonPlace +
            '</select>' +
            '</div>' +
            '<div class="fl inputRight"  id="calendarShow"><label for="departNames" class="fl">上课时间:&ensp;</label>' +
            '<div class="fl calendar">' +
            '<div class="input-group date form_date form_date3" data-date="" data-date-format="yyyy" data-link-field="dtp_input2" data-link-format="yyyy">' +
            '<input class="form-control searchStart" size="16" type="text" value="" readonly="" id="changes_ability_text" placeholder="请选择时间">' +
            '<span class="input-group-addon" style="display:none"><span class="glyphicon glyphicon-remove"></span></span>' +
            '<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '<div class="fl inputRight"><label for="departNames">课节时间:&ensp;</label>' +
            '<select id="lessonTime" class="publicSelect" >' +
            '<option value="1" classNum="1">第一节</option>' +
            '<option value="1" classNum="2">第二节</option>' +
            '<option value="1" classNum="3">第三节</option>' +
            '<option value="1" classNum="4">第四节</option>' +
            '<option value="1" classNum="5">第五节</option>' +
            '</select>' +
            '</div>';
    }

    function locationInformationd(data) { //搜索
        var selectDepartment = ""; //院系
        for(key in data.departmentList) {//遍历院系列表
            selectDepartment += '<option value="1" departmentId="' + data.departmentList[key].departmentId + '">' + data.departmentList[key].departmentName + '</option>';
        }
        /*var major = ""; //专业
        for(key in data.professionList) {
            major += '<option value="1" professionId="' + data.professionList[key].professionId + '">' + data.professionList[key].professionName + '</option>';
        }*/

        return '<div class="fl inputRight"><label for="selectDepartment">院&ensp;&ensp;&ensp;&ensp;系:&ensp;</label>' +
            '<select id="commencementDepartment" class="publicSelect" >' +
            '<option value="1">请选择</option>' +
            selectDepartment +
            '</select>' +
            '</div>' +
            '<div class="fl inputRight"><label for="selectMajor">专&ensp;&ensp;&ensp;&ensp;业:&ensp;</label>' +
            '<select id="major" class="publicSelect" >' +
            '<option value="1">请选择</option>' +

            '</select>' +
            '</div>' +
            '<div class="fl inputRight"><label for="curriculum">课&ensp;&ensp;&ensp;&ensp;程:&ensp;</label><input  type="text" id="curriculum" class="publicText" placeholder="请输入课程名称" /></div>' +
            '<div class="fl publicBtn searchBtn">搜索</div>' +

            '<div class="fr publicBtn deleteCurriculum">批量删除</div>';
    }

    function tabelModel(data) { //列表

        var score=1;
        if(data.tabList[key].classNum==1){
            score="第一节课";
        }else if(data.tabList[key].classNum==2){
            score="第二节课";
        }else if(data.tabList[key].classNum==3){
            score="第三节课";
        }else if(data.tabList[key].classNum==4){
            score="第四节课";
        }else if(data.tabList[key].classNum==5){
            score="第五节课";
        }
        var type = "";
        if(data.tabList[key].selectMark == 1){
            type = "教师排课";
        }else{
            type = "学生选课";
        }
        return '<tr data-num="0">' +
            '<td class="col-lg-2"><input value="0" name="selecteds" type="checkbox" class="oneCheck" relationId="' + data.tabList[key].relationId + '"  courseId="' + data.tabList[key].courseId + '"/></td>' +
            '<td class="col-lg-10"  title="' + data.tabList[key].professionName + '">' + data.tabList[key].professionName + '</td>' +
            '<td class="col-lg-10"  title="' + data.tabList[key].courseName + '">' + data.tabList[key].courseName + '</td>' +
            '<td class="col-lg-10"  title="' +data.tabList[key].classDate+'&ensp;&ensp;'+ data.tabList[key].week+'&ensp;&ensp;'+ score + '">' +data.tabList[key].classDate+'&ensp;&ensp;'+ data.tabList[key].week+'&ensp;&ensp;'+ score + '</td>' +
            '<td class="col-lg-10"  title="'+ data.tabList[key].siteName + '">'+ data.tabList[key].siteName + '</td>' +
            '<td class="col-lg-10"  title="'+type + '">'+ type + '</td>' +
            '<td class="col-lg-4">' +
            '<a href="javascript:;" class="set">修改</a>' +
            '</td>' +
            '</tr>';

    }
    var loading1 = new Loading();//监控全局ajax添加loading
    loading1.init();
    $(document).ajaxSend(function(){
        loading1.show();

    });
    $(document).ajaxStop(function(){
        loading1.hide();

    });
    document.addEventListener('DOMSubtreeModified',function(e){//去除空格
        $(".publicText").attr("maxlength","20");


        $.map($(".publicText"),function (opt) {//长度限制
            maxLengthLimit.init(opt);
        });
        $(".publicText").bind('input propertychange',function(){

            var regy = /\s/g;
            if(regy.test($(this).val())){
                $(this).val($(this).val().replace(/\s|\xA0/g,"")) ;
            }
        });
    });
    var nowData = 1;
    var index = {
        init: function() {
            this.bind();
        },
        bind: function() {
            var self = this;
            this.data_content = {}; //搜索集
            this.tab_content = {}; //列表集
            this.parameter = {
                "pageNow": 1,
                "pageSize": 10
            };

            this.postData(this.parameter, nowData);

        },
        postData: function(par_data, nowData,hunt) { //获得搜索及列表数据
            var self = this;
            var parameter = par_data;

            $.ajax({
                type: "post",
                url: "skipManagerCourseTabMana",
                async: true,
                data: {
                    "jsonStr": JSON.stringify(parameter)
                },
                success: function(data, status, xhr) {
                    var new_data = JSON.parse(data);
                    if(new_data.result == "success"){
                        if(hunt) {
                            self.tab_content = new_data;

                            self.tab_add();
                        } else {

                            self.data_content = new_data;
                            self.tab_content = new_data;

                            self.add();
                            self.tab_add();
                        }

                        var sumpage = new_data.totalPage;
                        if(sumpage<1){sumpage=1;};
                        var nowpage = 1;
                        var pagenumber = 10;
                        var parame = parameter;
                        $(".tcdPageCode").createPage({
                            pageCount: sumpage, //总页数
                            current: nowpage, //当前页数
                            pageNumber: pagenumber, //每页显示数量
                            backFn: function(p) {

                                nowpage = p;

                                if(nowpage >= sumpage) {
                                    nowpage = sumpage;
                                }
                                if(!parameter) {
                                    parameter = {
                                        "pageNow": nowpage,
                                        "pageSize": 10
                                    };

                                } else {
                                    parameter.pageNow = nowpage;

                                }
                                $.ajax({
                                    type: "post",
                                    url: "skipManagerCourseTabMana",
                                    async: true,
                                    data: {
                                        "jsonStr": JSON.stringify(parameter)
                                    },
                                    async: true,
                                    success: function(msg) {
                                        //获取地点
                                        var msgNew = JSON.parse(msg);
                                        self.tab_content = msgNew;

                                        self.tab_add();
                                    },
                                    error: function(data, status, xhr) {
                                        var json = JSON.stringify({
                                            "pageName": "error"
                                        });
                                        window.location.href = "skipPage?jsonStr=" + json;

                                    }
                                });
                            }
                        });
                    }else{
                        if(new_data.failMsg == "暂无权限"){
                            parent.location.reload(true);
                        }
                    }

                },
                error: function(data, status, xhr) {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;

                }
            });
        },
        add: function() { //搜索追加
            var self = this;
            var data = self.data_content;

            $("#searchCriteria").html(locationInformationd(data));
            $("#commencementDepartment").on("change", function() {//院系联动专业
                if($("#commencementDepartment option:selected").attr("departmentId") == null) {

                    $("#major").html('<option value="1" >请选择</option>');
                } else {

                    var parameter = {
                        "departmentId": $("#commencementDepartment option:selected").attr("departmentId")
                    };

                    $.ajax({
                        type: "post",
                        url: "getProfessionListByDepmentId",
                        async: true,
                        data: {
                            "jsonStr": JSON.stringify(parameter)
                        },
                        success: function(data) {
                            //获取地点

                            var msgNew = JSON.parse(data);
                            var con = "";

                            for(key in msgNew.professionList) {
                                con += '<option value="1" professionId="' + msgNew.professionList[key].professionId + '">' + msgNew.professionList[key].professionName + '</option>';
                            }
                            $("#major").html(con);

                        },
                        error: function(data, status, xhr) {
                            var json = JSON.stringify({
                                "pageName": "error"
                            });
                            window.location.href = "skipPage?jsonStr=" + json;

                        }
                    });
                }
            });
            $(".funBox .searchBtn").off("click").click(function() { //搜索点击

                var courseName = $("#curriculum").val();
                var departmentId = $("#commencementDepartment option:selected").attr("departmentId");
                var professionId = $("#major option:selected").attr("professionid");
                var nowData = 1;
                if(verification.specialCode(courseName)!==true){
                    self.alert1("不能输入特殊字符(@/'\"#$%&^*)");
                    return;
                }

                var parameter = {
                    "courseName": courseName,
                    "departmentId": departmentId,
                    "professionId": professionId,
                    "pageNow": 1,
                    "pageSize": 10
                };
                var j=0;
                //遍历删除空元素
                for(i in parameter){
                    if(j==0){j++;continue;}
                    if(parameter[i]==null||parameter[i]==""){
                        delete parameter[i];
                    }
                    if(!isNaN(parameter[i])){
                        parameter[i]=Number(parameter[i]);
                    }
                }

                self.postData(parameter, nowData,1);
            });
            $(".deleteCurriculum").off("click").on("click", function() { //删除课程
                self.delListEvent();
            });

        },
        tab_add: function() { //列表追加

            var self = this;
            var data = self.tab_content;
            var table = string1;

            //data.selectList={};

            var i = 0;
            for(key in data.tabList) {
                i++;
            }

            if(i > 0) {

                for(key in data.tabList) {

                    table += tabelModel(data);
                }

                $(".mainContent .tableBox").html(table);
            } else {
                var trImg = "<tr><td colspan='7'><img style='margin: 80px auto 20px;' src='pc/images/ico_noneData.png'><p style='font-size:26px;color:#8a8a8a;width:100%;text-align:center;'>暂无数据</p></td/tr>";
                $(".mainContent .tableBox").html(string1 + trImg);
            }
            //设置列表宽度(最大为9)
            var numMax = 0;
            $(".tableBox tr th").each(function() {
                var str = $(this).attr("class");
                var num = str.lastIndexOf("col-lg-") + 7;
                var num1 = parseFloat(str.substring(num, num + 1));
                numMax += num1;
            });

            $(".tableBox tr th").each(function() {
                var str = $(this).attr("class");
                var num = str.lastIndexOf("col-lg-") + 7;
                var num1 = parseFloat(str.substring(num, num + 1));

                $(this).css("width",num1 / numMax * 100+ "%");
            });



            self.allCheckEvent();//调用全选删除
            $(".set").off("click").click(function() { //修改信息
                var $_self = self;
                var skipSaveRelationPage = {
                    "relationId": $(this).parents("tr").children("td").eq(0).children("input").attr("relationid")
                };

                $.ajax({
                    type: "post",
                    url: "skipSaveRelationPage",
                    async: true,
                    data: {
                        "jsonStr": JSON.stringify(skipSaveRelationPage)
                    },

                    success: function(msg) {
                        var self = $_self;

                        var msgNew = JSON.parse(msg);
                        $("#Popup .pop_main").html(popup(msgNew));
                        $("#changes_ability_text").val(msgNew.relationMsg.classDate);
                        $("#lessonPlace option").each(function(){

                            if($(this).attr("siteid")==msgNew.relationMsg.siteId){

                                $(this).attr("selected","selected");
                            }
                        });

                        $("#lessonTime option").eq(msgNew.relationMsg.classNum-1).attr("selected","selected");
                        datePicker.datePickerMonth($("#changes_ability_text"));
                        $("#Popup").show();
                        $("#popupBackground").show();
                        $("#Popup .popup_contenthead span").off("click").click(function() { //叉点击
                            $("#Popup").hide();
                            $("#popupBackground").hide();
                        });
                        $("#Popup .preservation").off("click").click(function() { //弹窗点击
                            var classDate=$("#Popup #changes_ability_text").val();
                            var classNum=$("#lessonTime option:selected").attr("classNum");
                            var classId=$("#Popup .inputRight div").attr("classId");
                            var departmentId=$("#Popup .inputRight div").attr("departmentId");
                            var mainId=$("#Popup .inputRight").eq(4).children("div").attr("mainid");
                            var professionId=$("#Popup .inputRight").eq(1).children("div").attr("professionId");
                            var stuorteaId=$("#Popup .inputRight").eq(3).children("div").attr("stuorteaId");
                            var relationId=$("#Popup .inputRight div").attr("relationId");
                            var courseId=$("#Popup .inputRight").eq(2).children("div").attr("courseid");

                            var selectMark=$("#Popup .inputRight div").attr("selectMark");
                            var siteId=$("#lessonPlace option:selected").attr("siteId");

                            var saveRelationPageParameters = {
                                "classDate":classDate,
                                "classNum":parseInt(classNum),
                                // "classId":classId,
                                "courseId":parseInt(courseId),
                                "departmentId":parseInt(departmentId),
                                "mainId":parseInt(mainId),
                                "professionId":parseInt(professionId),
                                "relationId":parseInt(relationId),
                                "selectMark":1,
                                "siteId":parseInt(siteId),
                                "stuorteaId":stuorteaId
                            }
                            if(classDate==""){
                                self.alert1("请输入上课时间","fail");
                            }else if(siteId==null){
                                self.alert1("请选择上课地点","fail");
                            }else {
                                self.submits(saveRelationPageParameters);
                            }

                            $("#Popup").hide();
                        });
                    },
                    error: function(data, status, xhr) {
                        var json = JSON.stringify({
                            "pageName": "error"
                        });
                        window.location.href = "skipPage?jsonStr=" + json;

                    }
                });
            });

        },
        submits: function(saveRelationPageParameters) { //弹窗提交

            var self = this;
            $.ajax({
                type: "post",
                url: "saveRelationPage",
                async: true,
                data: {
                    "jsonStr": JSON.stringify(saveRelationPageParameters)
                },

                success: function(msg) {

                    var msgNew = JSON.parse(msg);

                    if(msgNew.result == "success") {
                        self.alert1("保存成功","success");
                    } else {
                        if(msgNew.failMsg){
                            self.alert1(msgNew.failMsg,"fail");
                        }else{
                            self.alert1("保存失败","fail");
                        }

                    }

                },
                error: function(data, status, xhr) {
                    var json = JSON.stringify({
                        "pageName": "error"
                    });
                    window.location.href = "skipPage?jsonStr=" + json;

                }
            });
        },
        alert1: function(content1,state) { //confirm提示

            Alert1.contenthead = "提示";
            Alert1.content = content1;

            Alert1.success = function() {
                if(state=="success"){
                    window.location.reload();
                    $("#popupBackground").hide();
                }
                if(state=="fail"){
                    $("#Popup").show();
                }
                Alert1.hide();

            };
            /*$(".alert_content" ).css({

                "line-height": "70px"
            })*/

            Alert1.init();
            Alert1.show();
        },
        allCheckEvent: function() {
            //全选
            allCheck.init("controlAll", "oneCheck");
        },
        delListEvent: function() { //批量删除
            var $_self = this;
            if($(".oneCheck[value=1]").length == 0) {
                Alert1.contenthead = "提示";
                Alert1.content = "请选择要删除的课程";
                Alert1.success = function() {};
                Alert1.init();
                Alert1.show();
            } else {

                confirm1.success = function() {
                    var list = [];
                    $(".box_1 tr td .oneCheck").each(function() {
                        if(parseInt($(this).val()) == 1) {
                            list.push($(this).attr("relationId"));

                        }

                    });

                    var deleteCurriculumparameters = list;
                    var self = $_self;
                    $.ajax({
                        type: "post",
                        url: "delClassTabs",
                        async: true,
                        data: {
                            "jsonStr": JSON.stringify(deleteCurriculumparameters)
                        },

                        success: function(msg) {

                            var msgNew = JSON.parse(msg);

                            if(msgNew.result == "success") {
                                self.alert1("删除成功","success");
                            } else {
                                //self.alert1(msgNew.failMsg,"success");
                                if(msgNew.failMsg){
                                    self.alert1(msgNew.failMsg,"success");
                                }else{
                                    self.alert1("删除失败","success");
                                }

                            }

                        },
                        error: function(data, status, xhr) {
                            var json = JSON.stringify({
                                "pageName": "error"
                            });
                            window.location.href = "skipPage?jsonStr=" + json;

                        }
                    });
                };
                var num = 0;
                $(".box_1 tr td .oneCheck").each(function() {
                    if(parseInt($(this).val()) == 1) {
                        num++;
                    }

                });
                if(num < 2) {
                    confirm1.content = "确定删除这门课程吗";
                } else {
                    confirm1.content = "确定删除这<a href='javascript:void(0)'>" + num + "</a>门课程吗";
                }

                confirm1.init();
                $(".alert_content a").css({
                    "margin": "2px",
                    "color": "#c82011",
                    "text-decoration": "underline"
                });
                confirm1.show();

            }
        }

    };
    index.init();

});